<?php


namespace app\common\controller;


use app\lib\exception\ParamException;
use think\Controller;
use think\Db;

/**
 * 与百度相关的
 */
class BaiduService extends Controller
{


    /**
     * 记录系统日志
     * @param string $behavior
     * @param array $arr
     */
    public function RecordSystemLog($uid,$behavior,$description)
    {
        $data['uid'] = $uid;
        $data['ip'] = $this->request->ip();
        $data['behavior'] = $behavior;
        $data['description'] = $description;
        model('SystemLog')->writeSystemLog($data);  // 日志入库
    }

    /**
     * 获取报告
     */
    public function getReportData($acc_id,$yesterday=0)
    {
        $account = Db::name('account')->find($acc_id);
        if($account['syn_status'] != 1){
            return json(['code' => 1001, 'msg' => '账户未开启同步']);
//            throw new ParamException(['msg'=>'账户未开启同步','errorCode'=>10001]);
        }
        if($account['syn_num'] == 0){
            $startDate= date('Y-m-d', strtotime('-1 month'));
        }else{
            if($yesterday){
                $startDate= date('Y-m-d', strtotime('-1 days'));
            }else{
                $startDate= date('Y-m-d');
            }
        }
        $endDate = date('Y-m-d');
        $columns = [
            // 2149145：账户报告--信息流
            '2149145'=>["date","userName","impression","click","cost","ctr","cpc","cpm","aggrFormClickSuccess","aggrFormSubmitSuccess"],
            // 2208157：账户报告--搜索
            '2208157'=>["date","userName","impression","click","cost","ctr","cpc","ocpcConversionsDetail5","ocpcConversionsDetail3"],
            // 2276038：计划报告--信息流
            '2276038'=>["date","userName","campaignNameStatus","impression","click","cost","ctr","cpc","cpm","aggrFormClickSuccess","aggrFormSubmitSuccess"],
            // 2290316：计划报告--搜索
            '2290316'=>["date","userName","campaignNameStatus","impression","click","cost","ctr","cpc","ocpcConversionsDetail5","ocpcConversionsDetail3"],
            // 2330652：单元报告--信息流
            '2330652'=>["date","userName","campaignNameStatus","adGroupNameStatus","impression","click","cost","ctr","cpc","cpm","aggrFormClickSuccess","aggrFormSubmitSuccess"],
            // 2284618：单元报告--搜索
            '2284618'=>["date","userName","campaignNameStatus","adGroupNameStatus","impression","click","cost","ctr","cpc","ocpcConversionsDetail5","ocpcConversionsDetail3"],
            // 2094816：创意报告--信息流
            '2094816'=>["date","userName","campaignNameStatus","adGroupNameStatus","ideaInfo","impression","click","cost","ctr","cpc","cpm","aggrFormClickSuccess","aggrFormSubmitSuccess"],
            // 2665235：创意报告--搜索
            '2665235'=>["date","userName","campaignNameStatus","adGroupNameStatus","ideaInfoMix","impression","click","cost","ctr","cpc","ocpcConversionsDetail5","ocpcConversionsDetail3"],
            // 2602783：关键词报告--搜索
            '2602783'=>["date","userName","campaignNameStatus","adGroupNameStatus","wInfoNameStatus","impression","click","cost","ctr","cpc","ocpcConversionsDetail5","ocpcConversionsDetail3"],
        ];

        foreach ($columns as $k=>$v){
            $this->saveReport($account, $k, $v, $startDate, $endDate);
        }

        Db::name('account')->where('id', $acc_id)->setInc('syn_num'); // 同步数加1

        return json(['code' => 1001, 'msg' => '未定义消息']);
    }

    /**
     * type=1 信息流， type=2 搜索
     */
    public function saveReport($account, $reportType,  $columns, $startDate, $endDate)
    {
        $res = $this->accountReport($account, $reportType,  $columns, $startDate, $endDate);
        if(isset($res[0]['rows'])){
            $rows = $res[0]['rows'];
            if($rows){
                $param = [];
                foreach ($rows as $K=>$v){
                    $param['date'] = $v['date'];
                    $param['impression'] = $v['impression'];
                    $param['click'] = $v['click'];
                    $param['cost'] = $v['cost'];
                    $param['ctr'] = $v['ctr'];
                    $param['cpc'] = $v['cpc'] ?? 0;

                    if($reportType == '2149145'){
                        $param['type'] = 1;
                        $param['userName'] = $v['userName'];
                        $param['cpm'] = $v['cpm'];
                        $param['aggrFormClickSuccess'] = $v['aggrFormClickSuccess'];
                        $param['aggrFormSubmitSuccess'] = $v['aggrFormSubmitSuccess'];
                        $where = [
                            'date'=>$v['date'],
                            'type'=>1,
                            'userName'=>$v['userName'],
                            'campaignId'=>0,
                            'adGroupId'=>0,
                            'ideaId'=>0
                        ];
                    }elseif ($reportType == '2208157'){
                        $param['type'] = 2;
                        $param['userName'] = $v['userName'];
                        $param['aggrFormClickSuccess'] = $v['ocpcConversionsDetail5'];
                        $param['aggrFormSubmitSuccess'] = $v['ocpcConversionsDetail3'];
                        $where = [
                            'date'=>$v['date'],
                            'type'=>2,
                            'userName'=>$v['userName'],
                            'campaignId'=>0,
                            'adGroupId'=>0,
                            'ideaId'=>0
                        ];
                    }elseif ($reportType == '2276038'){
                        $param['type'] = 1;
                        $param['userName'] = $v['userName'];
                        $param['campaignId'] = $v['campaignId'];
                        $param['campaignNameStatus'] = $v['campaignNameStatus'];
                        $param['cpm'] = $v['cpm'];
                        $param['aggrFormClickSuccess'] = $v['aggrFormClickSuccess'];
                        $param['aggrFormSubmitSuccess'] = $v['aggrFormSubmitSuccess'];
                        $where = [
                            'date'=>$v['date'],
                            'type'=>1,
                            'userName'=>$v['userName'],
                            'campaignId'=>$v['campaignId'],
                            'adGroupId'=>0,
                            'ideaId'=>0
                        ];
                    }elseif ($reportType == '2290316'){
                        $param['type'] = 2;
                        $param['userName'] = $v['userName'];
                        $param['campaignId'] = $v['campaignId'];
                        $param['campaignNameStatus'] = $v['campaignNameStatus'];
                        $param['aggrFormClickSuccess'] = $v['ocpcConversionsDetail5'];
                        $param['aggrFormSubmitSuccess'] = $v['ocpcConversionsDetail3'];
                        $where = [
                            'date'=>$v['date'],
                            'type'=>2,
                            'userName'=>$v['userName'],
                            'campaignId'=>$v['campaignId'],
                            'adGroupId'=>0,
                            'ideaId'=>0
                        ];
                    }elseif ($reportType == '2330652'){
                        $param['type'] = 1;
                        $param['userName'] = $v['userName'];
                        $param['campaignId'] = $v['campaignId'];
                        $param['campaignNameStatus'] = $v['campaignNameStatus'];
                        $param['adGroupId'] = $v['adGroupId'];
                        $param['adGroupNameStatus'] = $v['adGroupNameStatus'];
                        $param['cpm'] = $v['cpm'];
                        $param['aggrFormClickSuccess'] = $v['aggrFormClickSuccess'];
                        $param['aggrFormSubmitSuccess'] = $v['aggrFormSubmitSuccess'];
                        $where = [
                            'date'=>$v['date'],
                            'type'=>1,
                            'userName'=>$v['userName'],
                            'campaignId'=>$v['campaignId'],
                            'adGroupId'=>$v['adGroupId'],
                            'ideaId'=>0
                        ];
                    }elseif ($reportType == '2284618'){
                        $param['type'] = 2;
                        $param['userName'] = $v['userName'];
                        $param['campaignId'] = $v['campaignId'];
                        $param['campaignNameStatus'] = $v['campaignNameStatus'];
                        $param['adGroupId'] = $v['adGroupId'];
                        $param['adGroupNameStatus'] = $v['adGroupNameStatus'];
                        $param['aggrFormClickSuccess'] = $v['ocpcConversionsDetail5'];
                        $param['aggrFormSubmitSuccess'] = $v['ocpcConversionsDetail3'];
                        $where = [
                            'date'=>$v['date'],
                            'type'=>2,
                            'userName'=>$v['userName'],
                            'campaignId'=>$v['campaignId'],
                            'adGroupId'=>$v['adGroupId'],
                            'ideaId'=>0,
                            'wInfoId'=>0
                        ];
                    }elseif ($reportType == '2094816'){
                        $param['type'] = 1;
                        $param['userName'] = $v['userName'];
                        $param['campaignId'] = $v['campaignId'];
                        $param['campaignNameStatus'] = $v['campaignNameStatus'];
                        $param['adGroupId'] = $v['adGroupId'];
                        $param['adGroupNameStatus'] = $v['adGroupNameStatus'];
                        $param['ideaId'] = $v['ideaInfo']['ideaId'];
                        $param['ideaName'] = $v['ideaInfo']['ideaName'];
                        $param['cpm'] = $v['cpm'];
                        $param['aggrFormClickSuccess'] = $v['aggrFormClickSuccess'];
                        $param['aggrFormSubmitSuccess'] = $v['aggrFormSubmitSuccess'];
                        $where = [
                            'date'=>$v['date'],
                            'type'=>1,
                            'userName'=>$v['userName'],
                            'campaignId'=>$v['campaignId'],
                            'adGroupId'=>$v['adGroupId'],
                            'ideaId'=>$v['ideaInfo']['ideaId']
                        ];
                    }elseif ($reportType == '2665235'){
                        $param['type'] = 2;
                        $param['userName'] = $v['userName'];
                        $param['campaignId'] = $v['campaignId'];
                        $param['campaignNameStatus'] = $v['campaignNameStatus'];
                        $param['adGroupId'] = $v['adGroupId'];
                        $param['adGroupNameStatus'] = $v['adGroupNameStatus'];
                        $param['ideaId'] = $v['ideaInfoMix']['ideaId'];
                        $param['ideaName'] = $v['ideaInfoMix']['ideaTitle'];
                        $param['aggrFormClickSuccess'] = $v['ocpcConversionsDetail5'];
                        $param['aggrFormSubmitSuccess'] = $v['ocpcConversionsDetail3'];
                        $where = [
                            'date'=>$v['date'],
                            'type'=>2,
                            'userName'=>$v['userName'],
                            'campaignId'=>$v['campaignId'],
                            'adGroupId'=>$v['adGroupId'],
                            'ideaId'=>$v['ideaInfoMix']['ideaId']
                        ];
                    }elseif ($reportType == '2602783'){
                        $param['type'] = 2;
                        $param['userName'] = $v['userName'];
                        $param['campaignId'] = $v['campaignId'];
                        $param['campaignNameStatus'] = $v['campaignNameStatus'];
                        $param['adGroupId'] = $v['adGroupId'];
                        $param['adGroupNameStatus'] = $v['adGroupNameStatus'];
                        $param['wInfoNameStatus'] = $v['wInfoNameStatus'];
                        $param['wInfoId'] = $v['wInfoId'];
                        $param['aggrFormClickSuccess'] = $v['ocpcConversionsDetail5'];
                        $param['aggrFormSubmitSuccess'] = $v['ocpcConversionsDetail3'];
                        $where = [
                            'date'=>$v['date'],
                            'type'=>2,
                            'userName'=>$v['userName'],
                            'campaignId'=>$v['campaignId'],
                            'adGroupId'=>$v['adGroupId'],
                            'wInfoId'=>$v['wInfoId']
                        ];
                    }

                    $param['admin_id'] = $account['admin_id'];
                    $param['create_time'] = time();
                    $param['update_time'] = time();

                    $one = model('BaiduReport')->where($where)->find();
                    if($one){
                        model('BaiduReport')->where('id',$one['id'])->delete();
                    }
                    $res_db = Db::name('baidu_report')->insert($param);
                    if(!$res_db){
                        trace($param,'error');
                    }
                }

            }else{
                $this->RecordSystemLog($account['admin_id'],'manage/BaiduService/saveReport','未获取到百度渠道账户【'.$reportType.'】数据');
            }
        }
    }

    /**
     * 账户报告
     */
    public function accountReport($account, $reportType, $columns, $startDate, $endDate)
    {
        $service = 'OpenApiReportService/getReportData';
        $body = [
            'columns' => $columns,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'reportType' => $reportType,
            'sorts' => [],
            'filters' => [],
            'timeUnit' => 'DAY',
            'startRow' => 0,
            'rowCount' => 400,
            'needSum' => false,
        ];

        return $this->joinParam($account, $service, $body);
    }

    /**
     * 获取落地页
     */
    public function getPageList($account)
    {
        $service = 'JmySiteService/getPageList';
        $body = [
            'pageNum' => 1,
            'pageSize' => 1000
        ];

        return $this->joinParam($account, $service, $body);
    }

    public function getPromotionUrls($account,$type)
    {
        $service = 'TraceUrlService/getPromotionUrls';
        $body = [
            'optFrom' => $type,
            'showType' => 0,
            'limit' =>  [0, 500]
        ];

        return $this->joinParam($account, $service, $body);
    }

    /**
     * 拼接参数，发送请求
     */
    public function joinParam($account, $service, $body)
    {
        $url = 'https://api.baidu.com/json/sms/service/'.$service;
        $data  = [
            'header' => [
                'username' => $account['acc_name'],
                'password' => $account['acc_password'],
                'token' => $account['api_token']
            ],
            'body' => $body
        ];
        $res_json = postJson($url, $data);trace($res_json,'error');
        $res = json_decode($res_json, true);

        $res_status = $res['header']['status'] ?? -1;
        if($res_status === 0){
            return $res['body']['data'];
        }else{
            trace(json_encode($data, JSON_UNESCAPED_UNICODE),'error');
            trace($res_json,'error');
            model('Account')->save(['syn_status'=>2],['id'=>$account['id']]);
            throw new ParamException(['msg'=>$res['header']['failures'][0]['message'] ?? '请求失败','errorCode'=>20001]);
        }
    }
}